<template>
  <div>
    <!-- show-checkbox  节点是否被选择,就是显示复选框组件 -->
    <!-- check-strictly  实现父子组件不相互关联 -->
    <el-tree ref="tree" node-key="id" :data="data" check-strictly show-checkbox default-expand-all :props="{label:'name'}" />

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 导入获取权限详情
import { getPermissionList } from '@/api/permission'
// 导入根据id获取角色详情
import { getRoleFn, assignPerm } from '@/api/setting'
// 导入扁平数据转树形结构
import { treeFn } from '@/utils'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      data: [] // 权限树形结构
    }
  },
  created() {
    // 调用获取权限详情方法
    this.getPermissionList()

    // 调用获取角色详情方法
    this.getRoleFn()
  },
  methods: {
    // 获取角色详情方法
    async getRoleFn() {
      const res = await getRoleFn(this.roleId)
      // setCheckedNodes设置目前勾选的节点
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },
    // 获取权限详情
    async getPermissionList() {
      const res = await getPermissionList()
      this.data = treeFn(res.data, '0')
    },
    // 取消按钮
    cancelButton() {
      this.$emit('close')
    },

    // 设置权限按钮
    async setRolesBtn() {
      // 获取已经勾选的角色节点
      const permIds = this.$refs.tree.getCheckedKeys()
      const res = await assignPerm({ id: this.roleId, permIds })
      // console.log(res)
      this.$message.success(res.message)
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
